﻿
package extremefx.tools {
	import flash.utils.ByteArray;	
	/**
	 * @author Marcelo Volmaro
	 */
	public class Hex {
		/**
		 * Converts an hex string to a byte array.
		 * Support straight hex, or colon-laced hex.
		 * (that means 23:03:0e:f0 or 23:3:e:f0)
		 * Whitespace characters are ignored.
		 * @param pHex a string composed of hex pairs
		 * @return the decoded string as a <code>ByteArray</code>
		 */
		public static function toArray(pHex:String):ByteArray {
			pHex = pHex.replace(/\s/gm,'');
			var a:ByteArray = new ByteArray();
			var i:uint;
			
			if (pHex.indexOf(":") == -1){
				if (pHex.length&1 == 1) pHex="0"+pHex;
				for (i=0; i<pHex.length; i+=2) {
					a[i/2] = parseInt(pHex.substr(i,2),16);
				}
				
			} else {
				var b:Array = pHex.split(":");
				for (i=0; i<b.length; ++i) {
					a[i] = parseInt(b[i],16);
				}
			}
			
			return a;
		}
		
		/**
		 * Converts a byte array into an hex string. Optionally, hex values can be sepparated by a colon.
		 * @param pArray the <code>ByteArray</code> to convert into hex values.
		 * @param pColons true if hex values should be sepparated by colons, false if not.
		 * @return a string composed of hex numbers that represents the passed <code>ByteArray</code>.
		 */
		public static function fromArray(pArray:ByteArray, pColons:Boolean=false):String {
			var a:Vector.<String> = new Vector.<String>();
			for (var i:uint=0;i<pArray.length;++i) {
				a.push(("0"+pArray[i].toString(16)).substr(-2,2));
			}
			
			return a.join(pColons ? ":" : "");
		}
		
		/**
		 * Converts an hex string into a normal (UTF-8) string.
		 * @param pHex the hex string to decode into a string.
		 * @return a UTF-8 string decoded from pHex
		 */
		public static function toString(pHex:String):String {
			var a:ByteArray = toArray(pHex);
			return a.readUTFBytes(a.length);
		}
		
		
		/**
		 * Converts a (UTF-8) string into an hex string.
		 * @param pStr the string to be encoded into hex.
		 * @return a hex string encoded from the UTF-8 string pStr
		 */
		public static function fromString(pStr:String, pColons:Boolean=false):String {
			var a:ByteArray = new ByteArray();
			a.writeUTFBytes(pStr);
			return fromArray(a, pColons);
		}
	}
}
